package com.zxh.blog.util.excel;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * excel的所有列的配置
 * @author yintian.llj
 * @version $Id: ExcelColumnsConfigMap, v0.1 2018年05月21日 下午8:39 yintian.llj Exp $
 */
public class ExcelColumnsConfigMap {

  /**
   * 所有列的配置, 列头名为key
   */
  private Map<String, ExcelColumnConfigModel> configModelMap = new HashMap<>();

  public ExcelColumnsConfigMap(Map<String, ExcelColumnConfigModel> configModelMap) {
    this.configModelMap = configModelMap;
  }

  /**
   * 某列是否可为空
   * @param headerName
   * @return
   */
  public boolean canEmpty(String headerName) {
    ExcelColumnConfigModel columnConfigModel = configModelMap.get(headerName);
    return columnConfigModel == null || !columnConfigModel.canEmpty();
  }

  /**
   * 获取某列的配置
   * @param headerName
   * @return
   */
  public Optional<ExcelColumnConfigModel> getConfig(String headerName) {
    ExcelColumnConfigModel field = configModelMap.get(headerName);
    return Optional.ofNullable(field);
  }

  /**
   * 获取表头信息
   * 用于写excel时，先写表头
   * @return
   */
  public List<String> getHeaderName() {
    Set<Map.Entry<String, ExcelColumnConfigModel>> entries = configModelMap.entrySet();
    Iterator<Map.Entry<String, ExcelColumnConfigModel>> iterator = entries.iterator();
    List<String> list = new ArrayList<>();
    for (int i = 0; i < configModelMap.size(); i++) {
      list.add("");
    }
    int index = 0;
    while (iterator.hasNext()) {
      ExcelColumnConfigModel excelColumnConfigModel = iterator.next().getValue();
      if(excelColumnConfigModel.getColIndex() >= configModelMap.size()) {
      }
      if (-1 != excelColumnConfigModel.getColIndex()) {
        list.set(excelColumnConfigModel.getColIndex(), excelColumnConfigModel.getHeaderName());
      } else {
        list.set(index, excelColumnConfigModel.getHeaderName());
        index++;
      }
    }
    return list;
  }

  /**
   * 解析注解配置
   * @param clz
   * @return
   */
  public static ExcelColumnsConfigMap parse(Class clz) {
    Map<String, ExcelColumnConfigModel> outNameFieldSettings = new HashMap<>();
    for (Field field : ReflectUtils.getAllFields(clz)) {
      ExcelHeaderConfig a = field.getAnnotation(ExcelHeaderConfig.class);
      if (a != null && StringUtils.isNotBlank(a.headerName())) {
        ExcelColumnConfigModel excelFieldConfigModel = new ExcelColumnConfigModel(a.name(), a.headerName(), a.canEmpty(), a.colIndex());
        outNameFieldSettings.put(a.headerName(), excelFieldConfigModel);
      }
    }
    return new ExcelColumnsConfigMap(outNameFieldSettings);
  }
}
